package neu.soft.service.impl;

import com.alibaba.fastjson.JSON;
import neu.soft.constant.OrderStatus;

import neu.soft.constant.OrderType;
import neu.soft.entity.NormalOrder;
import neu.soft.entity.NormalOrderInfo;
import neu.soft.entity.User;
import neu.soft.feignclient.WarehouseFeignClient;
import neu.soft.mapper.OrderMapper;
import neu.soft.mapper.UserMapper;
import neu.soft.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WarehouseFeignClient warehouseFeignClient;

    /**
     * @return
     * 查询所有的订单
     */
    @Override
    public List<NormalOrder> findAllOrder() {
        List<NormalOrder> allOrder = orderMapper.findAllOrder();//加载所有客户
        for (NormalOrder order:allOrder
        ) {
            List<NormalOrderInfo> allOrderInfo = orderMapper.findAllOrderInfoById(order.getOid());//加载这个客户的商品
            order.setShoppingList(allOrderInfo);
            //如果是换货单就把换货信息加上
            if(order.getType()==OrderType.EXCHANGE_ORDER){
                List<NormalOrderInfo> allNewOrderInfo = orderMapper.findNewOrderInfosById(order.getOid());//加载这个客户的商品
                order.setNewShoppingList(allNewOrderInfo);
            }
        }
//        List<String> ids=allOrder.stream().filter(a->a.getShoppingList().size()==0).map(a->a.getOid()).collect(Collectors.toList());
//        ids.forEach(System.out::println); //获取没有购买商品的客户id
 //       allOrder.removeIf(a->a.getShoppingList().size()==0);  //不显示没有商品列表的订单
        return allOrder;
    }
@Override
  //根据用户id查找用户的所有订单
    public List<NormalOrder> findUserOrder(Map<String,Object>map){
        String uid= map.get("uid").toString();
    System.out.println(map.get("uid"));
        if(uid==null){
            return null;
        }
        List<NormalOrder> allOrder = orderMapper.findUserOrder(uid);//加载所有客户
    if(allOrder==null){
        return null;
    }
        for (NormalOrder order:allOrder
        ) {
            List<NormalOrderInfo> allOrderInfo = orderMapper.findAllOrderInfoById(order.getOid());//加载这个客户的商品
            order.setShoppingList(allOrderInfo);
            //如果是换货单就把换货信息加上
            if(order.getType()==OrderType.EXCHANGE_ORDER){
                List<NormalOrderInfo> allNewOrderInfo = orderMapper.findNewOrderInfosById(order.getOid());//加载这个客户的商品
                order.setNewShoppingList(allNewOrderInfo);
            }
        }
//        List<String> ids=allOrder.stream().filter(a->a.getShoppingList().size()==0).map(a->a.getOid()).collect(Collectors.toList());
//        ids.forEach(System.out::println); //获取没有购买商品的客户id
        //       allOrder.removeIf(a->a.getShoppingList().size()==0);  //不显示没有商品列表的订单
        return allOrder;
    }

    //抽离方法，换货新增和正常下单复用
    public boolean add(NormalOrder normalOrder, List<NormalOrderInfo>orderInfos) {
        //一个订单有多个商品
        //向users表添加user
        User user = new User();
        user.setLoc(normalOrder.getLoc());
        User usertemp=userMapper.findById(normalOrder.getRecv());
        user.setUsername(usertemp.getUsername());
        user.setTele(normalOrder.getTele());
      //  userMapper.add(user);
        //数据库的recv实际上是uid
       // normalOrder.setRecv(user.getUid());
        int res1 = orderMapper.addOrder(normalOrder);//表示订单信息改变的表中信息条数，一般只为1
        int res2 =addOrderInfo(normalOrder, orderInfos);//表示订单对应的商品信息或者时新商品信息改动的条数
        //如果订单和商品信息都添加，改动的表的行数大于等于2，否则就说明插入失败，需要查看添加商品信息是否成功

        return (res1 + res2 >= 2);
    }

    //抽离方法以便复用，添加订单的商品信息，可以是新商品信息也可以时原商品信息
    public int addOrderInfo(NormalOrder normalOrder, List<NormalOrderInfo>orderInfos){
        int res =0;//记录插入几条信息
        if (orderInfos == null || orderInfos.size() == 0) {
            return 0;
        }
        for (NormalOrderInfo orderinfo:orderInfos
        ) {
            Map<String,Object> map =  JSON.parseObject(JSON.toJSONString(orderinfo), Map.class);
            map.put("oid",normalOrder.getOid());
            //判断是不是换货单，如果时就往neworderinfo的表里面插入
            if (normalOrder.getType() == OrderType.EXCHANGE_ORDER){
                res +=  orderMapper.addNewOrderInfo(map);
            }else {
                res +=  orderMapper.addOrderInfo(map);

            }
        }
        return res;
    }


    /**
     * @param normalOrder 添加订单信息
     * @return
     */
    @Override
    public NormalOrder addOrder(NormalOrder normalOrder) {
        List<NormalOrderInfo> shoppingList;
        if (normalOrder.getType()==OrderType.EXCHANGE_ORDER){
          shoppingList =normalOrder.getNewShoppingList();
        }else{
            shoppingList = normalOrder.getShoppingList();
        }
            normalOrder.setTotalPay(getTotalPay(shoppingList));
        if(normalOrder.getType()==null){
            normalOrder.setType(OrderType.NORMAL_ORDER);
        }
        if(add(normalOrder,shoppingList)){
            return normalOrder;
        }
      return null;
    }
    public BigDecimal getTotalPay(List<NormalOrderInfo>shoppingList){
        BigDecimal totalPrice = BigDecimal.ZERO;
        for(NormalOrderInfo shoppingINfo :shoppingList){
             BigDecimal numBigDecimal = new BigDecimal(shoppingINfo.getShoppingNum());
            BigDecimal price = shoppingINfo.getShoppingPrice();
            BigDecimal product = numBigDecimal.multiply(price);
            totalPrice = totalPrice.add(product);
        }
        return totalPrice;
    }

    /**
     * @param map 包含要取消的订单oid
     */
    @Override
    public boolean cancelOrder(Map<String,Object>map) {

        NormalOrder normalOrder = orderMapper.findByOId(map);
        if(normalOrder!=null){
            if(normalOrder.getStatus().getCode()< OrderStatus.Have_Distributed.getCode()){
                map.put("status",OrderStatus.Invalid_Order);
                orderMapper.changeOrderStatus(map);
                return true;
            }
        }
        return false;
    }


    /**
     * @param map String  oid 处理退货单流程，返回一个退货单
     * @return
     */
    @Override
    public NormalOrder returnSales(Map<String,Object> map) {
        NormalOrder normalOrder = findById(map);//先看看有没有这个订单
        if (normalOrder!=null){

            map.put("type", OrderType.RETURN_ORDER);
            int res = orderMapper.changOrderType(map);
            if(res==1){
                return findById(map);
            }
        }
        return null;
    }

    /**
     * @param normalOrder 处理换货单流程
     */
    @Override
    public NormalOrder exchangeSales(NormalOrder normalOrder) {

        List<NormalOrderInfo>newList = normalOrder.getNewShoppingList();
        //先看有没有换货后的商品
        if (newList==null){
            return null;
        }
        Map<String,Object> map= new HashMap<>();
        map.put("oid",normalOrder.getOid());
        map.put("type",OrderType.EXCHANGE_ORDER);
        System.out.println("原订单的id"+normalOrder.getOid());
        orderMapper.changOrderType(map);
        //记录新商品完毕
        map.put("status",OrderStatus.Ready_To_Distribute);

       changeOrderStatus(map);
        addOrderInfo(normalOrder,newList);
        //生成新订单
       // addOrder(normalOrder);
       // map.replace("oid",normalOrder.getOid());
       // System.out.println("新订单的id"+normalOrder.getOid());
        return findById(map);

    }

    /**
     * @return
     */
    @Override
    public Map<String,Object> lackSales(NormalOrder normalOrder) {
        Map<String,Object> map = new HashMap<>();
        map.put("shopping",   normalOrder.getShoppingList());
        map.put("oid",  normalOrder.getOid());
        return map;
    }

    /**
     * @param map
     * @return
     */
    @Override
    public int deleteUselessOrder(Map<String, Object> map) {
        if(map.get("oid")!=null){
            return orderMapper.deleteUselessOrder(map);
        }else {
            return 0;
        }

    }

    /**
     * @param map 参数需要oid 和 status
     */
    @Override
    public boolean changeOrderStatus(Map<String, Object> map) {
        return (orderMapper.changeOrderStatus(map)==1);//每次只改一条数据
    }

    /**
     * @param map 参数需要oid
     *
     */
    @Override
    public OrderStatus showStatus(Map<String, Object> map) {

        if(map.get("oid")!=null){
            OrderStatus orderStatus = orderMapper.showOrderStatus(map);
            if(orderStatus !=null){
                return orderStatus;
            }
        }
        return null;
    }

    /**
     * @param map 参数需要 oid
     */
    @Override
    public NormalOrder findById(Map<String,Object> map) {
       String oid =  map.get("oid").toString();
        if(oid!=null){
            NormalOrder normalOrder = orderMapper.findByOId(map);
            List<NormalOrderInfo> orderInfos = orderMapper.findAllOrderInfoById(oid);
            normalOrder.setShoppingList(orderInfos);
            return normalOrder;
        }
        return null;
    }
}
